import { defineStore } from 'pinia';
import { logout as userLogout, getAllUser } from '@/api/user';
import { getAllRole, getNetWorkDetail, getOrgAll } from '@/api/syssetting';
import { setToken, clearToken } from '@/utils/auth';
import { getarchiveCategory } from '@/api/dataCenter';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';
import { request } from '@/utils/$http';
import { getDocTypeList } from '@/api/dataCenter';
import { getDeptSelect } from '@/api/syssetting';
import { getGlobalUserInfo } from '@/api/global';
import generateRoutes from '@/utils/generateRoutes';
import router from '@/router/index';
import { NOT_FOUND_ROUTE } from '@/router/routes/base';
import { getGeoProvice } from '@/api/policy';
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    // 新增的
    user_address: undefined,
    user_avatar: undefined,
    user_birthday: undefined,
    user_email: undefined,
    user_gender: undefined,
    user_home_telephone: undefined,
    user_id: undefined,
    user_org_id: undefined,
    user_mobile: undefined,
    user_name: undefined,
    user_nick_name: undefined,
    user_postal_code: undefined,
    user_qq: undefined,
    user_signature: undefined,
    user_wechat: undefined,
    user_work_telephone: undefined,
    // 新增的
    role: '',
    allUser: undefined,
    allDept: undefined,
    allFileTypes: undefined,
    allOrg: undefined,
    allRole: undefined,
    allprovices: undefined,
    allDanganTypes: undefined,
    pageInfo: undefined,
  }),
  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
    userID(state: UserState) {
      return state.user_id;
    },
    allUserInfo(state: UserState) {
      return state.allUser;
    },
    allDepts(state: UserState) {
      return state.allDept;
    },
    allProvice(state: UserState) {
      return state.allprovices;
    },
    allTypeFiles(state: UserState) {
      return state.allFileTypes;
    },
    allOrgList(state: UserState) {
      return state.allOrg;
    },
    allDanganTypeList(state: UserState) {
      return state.allDanganTypes;
    },
  },

  actions: {
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },
    resetInfo() {
      this.$reset();
    },
    async fetchAllData() {
      const res = await getAllUser();
      const deptas = await getDeptSelect();
      const allOrgList = await getOrgAll();
      const allroleList = await getAllRole();
      const types = await getDocTypeList({
        page_size: 1000,
      });
      const allproviceslist = await getGeoProvice();
      const allCgType = await getarchiveCategory({});
      this.setInfo({ allDanganTypes: allCgType.data.list });
      this.setInfo({ allprovices: allproviceslist.data });
      this.setInfo({ allUser: res.data });
      this.setInfo({ allFileTypes: types.data.list });
      this.setInfo({ allDept: deptas.data });
      this.setInfo({ allOrg: allOrgList.data });
      this.setInfo({ allRole: allroleList.data });
    },
    // Login
    async login(loginForm: any) {
      try {
        const res = await request.post('/login/login', loginForm);
        setToken(res.data.access_token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    async getUserInfo() {
      return new Promise(async (resolve, reject) => {
        try {
          const appStore = useAppStore();
          const userInfo = await getGlobalUserInfo();
          appStore.setRoutes(generateRoutes(userInfo.data.auth));
          appStore.routes.forEach((route: any) => {
            router.addRoute(route);
          });
          router.addRoute(NOT_FOUND_ROUTE);
          this.setInfo(userInfo.data); // 注意这里的this指向是否正确
          const pageInfo = await getNetWorkDetail();
          pageInfo.data.web_logo = ` ${import.meta.env.VITE_API_BASE_URL}${
            pageInfo?.data?.web_logo
          }
          `;
          this.setInfo({ pageInfo: pageInfo.data });
          resolve();
        } catch (error) {
          reject(error);
        }
      });
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
